//: Playground - noun: a place where people can play

// Created by zhumin   2017.9.13

import UIKit

var str = "Hello, playground"

print("hello,world!!")

// var 定义变量
var myVariable = 42

myVariable = 50

// let 定义常量
let myConstant = 42

// 未指定数据类型
let implicitInteger = 70
let implicitDouble = 70.0

// 指定数据类型 用冒号分隔
let explicitDouble: Double = 70

let label = "The width is "

let width = 94

// 字符串拼接
let widthLabel = label + String(width)

let apples = 3

let oranges = 5

let appleSummary = "I have \(apples) apples"

let fruitSummary = "I have \(apples) apples and \(oranges) oranges"

/**
 *  Swift 4 黑科技   三引号
    字符之间有空行也不影响排版
 */

/**
 *  let quotation = """
    Even though there's whitespace
                to the left,
    the actual lines aren't
                indented.
    Except for this line.
    Double quotes(") can appear
                without being
                escaped.
 
    I still have \(apples + 
                oranges) pieces of
                fruit.
    """
 */

// 数组定义方式
var shoppingList = ["catfish", "water", "tulips", "bluePaint"]

// 字典定义方式
var occupationsDic = ["Malcolm": "Captain", "Kaylee": "Mechanic"]
occupationsDic["Jayne"] = "Public Relations"

// 创建空的数组(指定类型)
let emptyArray = [String]()

// 创建空的字典（指定类型）
let emptyDictionary = [String: Float]()

// 如果可以推断其类型则可写成如下形式
shoppingList = []
occupationsDic = [:]

// 循环遍历
let individualScores = [75, 43, 103, 87, 12]
var teamScore = 0

for score in individualScores {
    if score > 50 {
        teamScore += 3
    } else {
        teamScore += 1
    }
}

print(teamScore)

// 可选类型
var optionalString: String? = "hello"
print(optionalString == nil)

var optionalName: String? = "John Appleseed"
var greeting = "Hello"

if let name = optionalName {
    greeting = "Hello, \(name)"
} else {
    greeting = "Hello"
}

let nickName: String? = nil
let fullName: String = "John Appleseed"
let informalGreeting = "Hi \(nickName ?? fullName)"

// swith 用法 warning: default不能省略，不然会报错
let vegetable = "red pepper"
switch vegetable {
case "celery":
    print("Add some raisins and make ants on a log")
case "cucumber", "watercress":
    print("That would make a good tea sandwich.")
case let x where x.hasSuffix("pepper"):
    print("Is it a spicy \(x)?")
default:
    print("Everything tastes good in soup.")
}

// 遍历字典
let interestingNumbers = [
    "Prime": [2, 3, 5, 7, 11, 13],
    "Fibonacci": [1, 1, 2, 3, 5, 8],
    "Square": [1, 4, 9, 16, 25],
]

var largest = 0
for (kind, numbers) in interestingNumbers {
    for number in numbers {
        if number > largest {
            largest = number
        }
    }
}
print(largest)

// while语法
var n = 2
while n < 100 {
    n *= 2
}
print(n)

var m = 2
repeat {
    m *= 2
} while m < 100
print(m)

// for循环
var total = 0
for i in 0..<4 {
    total += i
}
print(total)

// 函数（Functions）和 闭包（Closures）
// 1.函数的声明与调用
func greet(person: String, day: String) -> String {
    return "Hello \(person), today is \(day)."
}
greet(person: "Bob", day: "Tuesday")

// 如果没有外部名，函数第一个参数会缺省参数名
func greet2(_ person: String, on day: String) -> String {
    return "Hello \(person), today is \(day)."
}
greet2("John", on: "Wednesday")

// 元组
func calculateStatistics(scores:[Int]) -> (min: Int, max: Int, sum: Int){
    var min = scores[0]
    var max = scores[0]
    var sum = 0
    
    for score in scores {
        if score > max {
            max = score
        } else if score < min {
            min = score
        }
        sum += score
    }
    return (min, max, sum)
}
let statistics = calculateStatistics(scores: [5, 3, 100, 3, 9])
print(statistics.sum)
print(statistics.2)

